<?php
Yii::import('ext.widgets.EAbuse.AbuseData');
class AbuseAction extends Action {
    
    public $module;
    public $moduleId;
    
    public function run(){
        $this->loginRequired();
        $params=AbuseData::getData($this->module);
        if(in_array($this->moduleId, $params)){
            $result = $this->removeItem();
        }else{                    
            $result = $this->addItem();
        }

        if (isset($_POST['ajax'])){
            echo CJSON::encode(array(
                'result' => $result,
            ));
        } else {
            $this->controller->redirect(Yii::app()->request->urlReferrer);
        }   
    }
    
    public function addItem(){
        $model = new Abuse;
        $model->module_ = $this->module;
        $model->moduleId_ = $this->moduleId;
        if ($model->addRecord()) {
            AbuseData::add($this->module, $this->moduleId);
            $d = $this->module;
            $data = $d::model()->published()->findByPk($this->moduleId);
            if (!empty($data))
                $data->updateAbuseCounter();
            return 1;
        }else{
            return $model->getErrors();
        }
    }
    
    public function removeItem(){
        $data=Abuse::model()->module($this->module)->moduleId($this->moduleId)->userId(Yii::app()->user->id)->accessible()->find();
        if (empty($data))
            HttpStatus::code(404);
        if ($data->deleteRecord()) {
            AbuseData::delete($this->module, $this->moduleId);
            return 0;
        }
    }
    
}